package servlet;

import bean.AdminBean;
import dao.AdminDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登陆校验
 */
@WebServlet("/Login/Servlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LoginServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //登录的判断
        request.setCharacterEncoding("UTF-8");//设置编码方式防止乱码
        response.setContentType("text/html;charset=UTF-8");
        //获取账号和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        AdminDao userDao = new AdminDao();

        //对账号和密码进行判断
        boolean flag = false;
        flag = userDao.Login_verify(username, password);
        HttpSession session = request.getSession();


        //判断输入正确
        if (flag) {
            AdminBean user = new AdminBean();
            AdminDao admindao = new AdminDao();
            //更加账号和密码查找出读者的信息
            user = admindao.getAdminInfo(username, password);
            //将aid存入session中
            session.setAttribute("aid", "" + user.getAid());
            //设置session的失效时间
            session.setMaxInactiveInterval(3600);
            //根据status的值来判断是管理员，还是读者，status=1为管理员
            if (user.getStatus() == 1) {
                System.out.println("管理员");
                response.sendRedirect("../index1.html");
            } else {
                System.out.println("读者");
                response.sendRedirect("../index2.html");
            }
        } else {
            //没有找到对应的账号和密码，返回重新登录
            session.setAttribute("state", "密码错误");
            System.out.println("密码错误");
            response.sendRedirect("loginError.html");
        }
    }

}
